<template>
  <div class="cases">
    <!-- <el-button type="primary" @click="openDialog()">新增新闻</el-button> -->

    <el-table border :data="tableData"  style="width: 100%">
      <el-table-column type="index" label="序号" width="100" align='center'></el-table-column>
      <el-table-column prop="m" label="新闻标题" width="180"></el-table-column>
      <el-table-column prop="n" label="新闻图片">
        <template slot-scope="scope">
          <img style="width:100%" v-if="scope.row.n" :src="tupian(scope.row.n)" alt />
        </template>
      </el-table-column>
      <el-table-column prop="n" label="新闻内容">
      <template slot-scope="scope">
        <span v-if="scope.row.n">{{wenzi(scope.row.n)}}</span>
      </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align='center'>
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新闻编辑弹出框 -->
    <el-dialog title="新闻编辑" :visible.sync="dialogFormVisible" @close ="resetForms">
      <el-form :model="formData" :rules="rules" ref="formData">
        <el-form-item label="新闻标题" :label-width="formLabelWidth" prop="m">
          <el-input v-model="formData.m" autocomplete="off" class="autowidth" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="时间选择" required :label-width="formLabelWidth" >
      <el-form-item prop="s">
        <el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="选择日期" v-model="formData.s"></el-date-picker>
      </el-form-item>
        </el-form-item>
        <div v-for="(item, index) in formData.n" :key="index">
          <el-form-item label="新闻图片" :label-width="formLabelWidth" v-if="item.lx=='图片'">
          <el-upload
            ref="uploadref"
            class="avatar-uploader"
            action="/page/set"
            :headers="headers"
            :show-file-list="false"
            :on-success="successUpload(index)"
            :data="Imgdata"
            :file-list="fileList"
            :http-request="upload"
            :on-change="handleChange"
            :limit="1"
            accept=".jpg, .png"
          >
            <img v-if="item.nr" :src="item.nr" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-button  type="success" @click="determine(index)">修改当前图片</el-button>
          <el-button class="delleft" size="mini" @click="delopen(item)">删除</el-button>
        </el-form-item>
        <el-form-item label="新闻内容" :label-width="formLabelWidth" v-else>
            <el-input class="autowidth" autosize type="textarea" v-model="item.nr" autocomplete="off" @input="change()" placeholder="请输入内容"></el-input>
            <el-button class="del" size="mini" @click="delopen(item)">删除</el-button>
        </el-form-item>
        </div>
          <!-- 添加内容按钮 -->
          <el-popover
            class="addbunbox"
            placement="bottom"
            width="160"
            v-model="isvisible">
            <p style="text-align: center;">添加文字or图片</p>
            <div style="text-align: center;">
              <el-button type="primary" size="mini" @click="addText">文字</el-button>
              <el-button type="success" size="mini" @click="addPicture">图片</el-button>
            </div>
          <div slot="reference" type="primary" class="el-icon-circle-plus-outline addbun"></div>
          </el-popover>
          <!-- <div slot="footer" class="dialog-footer"> -->
            <el-form-item class="dialog-footer" label-width="70%">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleCreateOrModify">确 定</el-button>
            </el-form-item>
          <!-- </div> -->
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import qs from "qs"
export default {
  data() {
    return {
      dialogFormVisible: false,
      formLabelWidth: "120px",
      tableData: [],
      newtableData: [],
      formData: {
        m: '',
        n: '',
        s: null
      },
      options: {},
      headers: {},
      date: '', // 时间选择器
      isvisible: false,
      rules: {
        m: [
          { required: true, message: '请输入新闻标题', trigger: 'blur' },
        ],
        s: [
          { type: 'string', required: true, message: '请选择日期', trigger: 'change' }
        ]
      },
      newformData:{}, // 最终提交的数据
      index: '', // 当前项的索引值
      Uploadurl: '/upload/set', // 图片上传地址
      Imgdata: {
        view:'用户管理',
        code:'wzwh',
      },
      fileList:[], // 上传文件列表
      imgName: '', // 上传文件成功后得到的图片名称
      image: '' ,// 图片名称请求的图片地址
      imgindex: '', // 当前图片所在的位置
    };
  },
  created(){
    this.loadData();
  },
  computed:{
    // 筛选出所以符合类型的对象 渲染显示第一个
    wenzi(){
      return function(n){
        let newn=[]
        n.forEach(element => {
          if(element.lx=='文字'){
            newn.push(element)
          }
        });
        if(newn.length==0){
          return ""
        }else{
          return newn[0].nr
        }
      }
    },
    tupian(){
      return function(n){
        let newn=[]
        n.some(element => {
          if(element.lx=='图片'){
            newn.push(element)
          }
        });
        // console.log(newn);
        if(newn.length==0){
          return ""
        }else{
          return newn[0].nr
        }
      }
    }
  },
  methods: {
    successUpload(index) {
      // this.$refs.uploadref.clearFiles()
      // this.imgindex=index
      // console.log(this.index);
      // this.formData[this.index].n[index].nr = response;
    },
    handleChange(file, fileList) {
            this.fileList = fileList;
            console.log(this.fileList)
    },
    determine(index){
      this.imgindex=index
      console.log(this.imgindex);
    },
    // 自定义上传文件
    upload(){
        let fd = new FormData();
        fd.append("view", "用户管理"); 
        fd.append("code", "wzwh");
        // console.log(this.fileList);
        this.fileList.forEach(item=>{
            //文件信息中raw才是真的文件
            fd.append("up_files",item.raw);
            // console.log(fd.get('up_files'))
        })
        this.$http.post("/page/set",fd,)
        .then(async({ data:res}) =>{
          // console.log(res);
            if (res.code === '0') {
              // JSON.parse(res.data).forEach(element => {
              //   this.imgName=element
              // });
              this.imgName=JSON.parse(res.data)[0]
              console.log((this.imgName));
              const imgres = await this.$http.get('/page/get',{
                params:{
                  view: '系统后台',
                  code: 'wzxx',
                  data: {
                    mc: this.imgName
                  }
                }
              })
              this.image=imgres.request.responseURL
              this.formData.n[this.imgindex].nr = this.image
              // console.log(this.imgindex);
              console.log(this.formData);
              // console.log(this.formData[this.index]);
              this.$message.success('上传成功')
              this.fileList = []
            }else{
              this.$message.error('失败'+res.data)
            }
        })
    },
    loadData() {
      this.$http
        .get(
          "/data/get",{
          params:{
            view: "系统后台",
            code: "wzxx",
            data: JSON.stringify({fz:3})
          }
          }
        )
        .then(response => {
          this.tableData = (JSON.parse(response.data.data));
          this.tableData.forEach((element,index) => {
            if(typeof(element)=='string'){
              element=JSON.parse(element)
              this.tableData[index]=element
            }
          });
          window.console.log(this.tableData);
        })
        .catch(e => {
          this.$message({
            message: "网络或程序异常！" + e,
            type: "error"
          });
        });
    },
    openDialog() {
      // 清除数据
      this.formData.Id = 0;
      this.formData.Img = "";
      this.formData.Title = "";
      this.formData.Content = "";
      this.formData.Del = "";
      this.formData.CreateTime = new Date();

      this.dialogFormVisible = true;
    },
    // 修改
    handleCreateOrModify() {
      this.newformData=JSON.parse(JSON.stringify(this.formData))
      console.log(this.newformData);
      // console.log(this.$refs[formName]);
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post('/data/set',
            qs.stringify({
              view: '用户管理',
              code: 'wzwh',
              data: JSON.stringify({
                fz: 3,
                i:  this.index,
                sz: this.newformData
              })
            })
          )
          console.log(res);
          if(res.code=="0"){
            this.$message({
              message: '编辑成功!',
              type: 'success'
            });
          }
          this.dialogFormVisible = false
        } else {
          this.$message.error('出错!');
          return false;
        }
        this.loadData()
      });
    },
    // 拿到选中行的index和数据
    handleEdit(index, row) {
      window.console.log(index, row);
      this.index = index
      // 深拷贝让formData不印象原先数据
      this.formData = JSON.parse(JSON.stringify(row));
      if(this.formData.n==undefined){
        this.formData.n = []
      }
      this.dialogFormVisible = true;
    },
    //时间格式化
    dateFormat: function(row) {
      //row 表示一行数据, CreateTime 表示要格式化的字段名称
      let t = new Date(row.CreateTime);
      return t.getFullYear() + "-" + (t.getMonth() + 1) + "-" + t.getDate();
    },
    // 添加文字
    addText() {
      this.formData.n.push({
        lx: "文字",
        nr: ""
      })
      this.isvisible = false
    },
    // 添加图片
    addPicture(){
      this.formData.n.push({
        lx: "图片",
        nr: ""
      })
      this.isvisible = false
    },
    // 关闭编辑对话框 初始化表单
    resetForms(){
      this.fileList = []
      this.$refs.formData.resetFields();
    },
    change() {
      this.$forceUpdate()
    },
    // 是否确定删除确认框
    delopen(item) {
      this.$confirm('确定是否删除该内容?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var index = this.formData.n.indexOf(item)
        if (index !== -1) {
          this.formData.n.splice(index, 1)
          // 删除不更新页面暂时解决方法 后续寻求其他方法
          this.isvisible = true
          this.isvisible = false
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    }
  }
};
</script>

<style lang="scss" scoped>
  .block{
    margin: 0 0 20px 50px;
  }
  // 添加内容选项小窗口
  .addbunbox{
    position: absolute;
    top: 20;
    left: 50%;
    transform: translate(-50%);
  }
  /* 添加内容按钮 */
  .addbun:before{
    position: absolute;
    left: 50%;
    top: 0;
    transform: translate(-50%);
    color: skyblue;
    font-size: 20px;
  }
  .dialog-footer{
    padding-top: 20px;
  }
  .autowidth{
    width: 400px;
  }
  .del{
    margin-left: 10px;
  }
  .delleft{
    position: absolute;
    top: 39%;
    left: 40%;
  }
  /deep/.el-dialog{
    border-radius: 20px;
    .el-dialog__header{
      border-radius: 20px 20px  0 0;
      background-color: skyblue;
      .el-dialog__title{
        font-weight: 600;
        color: white;
      }
    }
  }
</style>

